
GLFW3_H=glfw-3.3.2.bin.WIN32/include/GLFW/glfw3.h
GLFW_CONSTANTS_H=.glfw_constants.h
GLFW_FUNCTIONS_H=.glfw_functions.h

sed -r -e '/^#define *GLFW_/!d' \
    -e 's/\/\*.*$//' \
    -e 's/0x/#x/' \
    -e 's/^#define *//' "${GLFW3_H}" >${GLFW_CONSTANTS_H}

sed -r -e '/^GLFWAPI/!d' \
    -e 's/^GLFWAPI //' \
    -e 's/ [a-zA-Z_]*,//g' \
    -e 's/ [a-zA-Z_]*\)/)/g' \
    -e 's/\(void\)/()/g' \
    -e 's/;$//' "${GLFW3_H}" >${GLFW_FUNCTIONS_H}

GLFW_CONSTANT_NAMES="$(sed -r -e 's/^([^ ]*).*$/    \1/' ${GLFW_CONSTANTS_H})"
GLFW_CONSTANT_DEFINITIONS="$(sed -r -e 's/^([^ ]*) *(.*) *$/  (define \1 \2)/' ${GLFW_CONSTANTS_H})"

GLFW_FUNCTION_NAMES="$(sed -r -e 's/(.*) (glfw[^(]*)(.*)/    \2/' ${GLFW_FUNCTIONS_H})"
GLFW_FUNCTION_DEFINITIONS="$(sed -r -e 's/const //g' \
    -e 's/unsigned char\*/char*/g' \
    -e 's/char\*\*/uptr/g' \
    -e 's/char\*/string/g' \
    -e 's/(int|float|double)\*/(* \1)/g' \
    -e 's/uint(8|16|32|64)_t\*/(* unsigned-\1)/g' \
    -e 's/uint(8|16|32|64)_t/unsigned-\1/g' \
    -e 's/GLFW[a-zA-Z0-9_]*\*\*/uptr/g' \
    -e 's/GLFW[a-zA-Z0-9_]*(fun|proc|\*)/uptr/g' \
    -e 's/(VkInstance|VkSurfaceKHR|VkAllocationCallbacks|VkPhysicalDevice|VkResult)\*?/uptr/g' \
    -e 's/(.*) (glfw[^(]*)(.*)/  (define \2 (foreign-procedure __stdcall "\2" \3 \1))/' \
    ${GLFW_FUNCTIONS_H})"


GLFW_TYPES="$(sed -r -e '/typedef/!d' \
		  -e 's/typedef [^ ]* (\(\*)? ?(GLFW[^) ]*).*/  (define-ftype \2 uptr)/' ${GLFW3_H})"


# ${GLFW_TYPES}
#   (define-ftype uint32_t unsigned-32)
#   (define-ftype uint64_t unsigned-64)
#   (define-ftype int* (* int))
#   (define-ftype uint32_t* (* unsigned-32))
#   (define-ftype float* (* float))
#   (define-ftype double* (* double))
#   (define-ftype char** (* uptr))

  # (define GLFW_HAT_RIGHT_UP #x03) ;;(GLFW_HAT_RIGHT | GLFW_HAT_UP))
  # (define GLFW_HAT_RIGHT_DOWN #x06) ;;(GLFW_HAT_RIGHT | GLFW_HAT_DOWN))
  # (define GLFW_HAT_LEFT_UP #x09) ;;(GLFW_HAT_LEFT  | GLFW_HAT_UP))
  # (define GLFW_HAT_LEFT_DOWN #x0C) ;;(GLFW_HAT_LEFT  | GLFW_HAT_DOWN))
cat <<EOF >glfw/glfw.scm
(library (glfw glfw)
  (export
${GLFW_CONSTANT_NAMES}

${GLFW_FUNCTION_NAMES}
  )
  (import
    (chezscheme))

  (define libglfw (load-shared-object "glfw3.dll"))

${GLFW_CONSTANT_DEFINITIONS}

${GLFW_FUNCTION_DEFINITIONS}
)
EOF

sed -i -r \
    -e '/^ *\(define GLFW_HAT_RIGHT_UP/c\ \ (define GLFW_HAT_RIGHT_UP #x03) ;;(GLFW_HAT_RIGHT | GLFW_HAT_UP))' \
    -e '/^ *\(define GLFW_HAT_RIGHT_DOWN/c\ \ (define GLFW_HAT_RIGHT_DOWN #x06) ;;(GLFW_HAT_RIGHT | GLFW_HAT_DOWN))' \
    -e '/^ *\(define GLFW_HAT_LEFT_UP/c\ \ (define GLFW_HAT_LEFT_UP #x09) ;;(GLFW_HAT_LEFT  | GLFW_HAT_UP))' \
    -e '/^ *\(define GLFW_HAT_LEFT_DOWN/c\ \ (define GLFW_HAT_LEFT_DOWN #x0C) ;;(GLFW_HAT_LEFT  | GLFW_HAT_DOWN))' \
    glfw/glfw.scm
